package ua.at.tsvetkov.samizdat.activities;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;

import ua.at.tsvetkov.application.ActivityStack;
import ua.at.tsvetkov.application.AppConfig;
import ua.at.tsvetkov.net.NetCheck;
import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.Key;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.adapters.AdtSearchAuthors;
import ua.at.tsvetkov.samizdat.data.Data;
import ua.at.tsvetkov.samizdat.data.DataDownloader;
import ua.at.tsvetkov.samizdat.data.OnCompleteLoadListener;
import ua.at.tsvetkov.strings.Util;
import ua.at.tsvetkov.ui.Rout;
import ua.at.tsvetkov.util.Log;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

public class AcSearchAuthor extends AcTemplate {

	public static final int			DIALOG_LOAD	= 0;

	public ListView					listView;
	public AdtSearchAuthors			adt;

	protected View						searchView;
	protected FrameLayout			searchViewSpace;
	protected TextView				searchViewText;
	protected Button					searchViewButton;

	protected DataDownloader		dataDownloader;
	protected DataDownloader		searchDownloader;
	protected int						startPosition;
	protected TextView				textTitle;
	protected TextView				textInfo;
	protected TextView				textPages;
	protected TextView				textView;
	protected View						textFrameView;
	protected ZoomControls			textZoomControls;
	protected SeekBar					textSeekBar;
	protected ScrollView				textScrollView;

	private String[]					data;

	private String						code;
	private String						count;
//	private String						text;
	private String						urlStr;
	private String						fileName;
	private InputMethodManager		inputManager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		searchView = mInflater.inflate(R.layout.ac_search_author, null);
		searchViewSpace = (FrameLayout) searchView.findViewById(R.id.AcSearchAuthorWorkingSpace);
		searchViewText = (TextView) searchView.findViewById(R.id.AcSearchAuthorSearchField);
		searchViewButton = (Button) searchView.findViewById(R.id.AcSearchAuthorButton);
		mainFrame.addView(searchView);
		adt = new AdtSearchAuthors(this);
		listView = (ListView) findViewById(R.id.AcSearchAuthorListView);
		listView.setAdapter(adt);
		listView.setFastScrollEnabled(true);
		searchViewButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				check();
			}

		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String[] authorData = Util.split((String) adt.getItem(position), Data.AUTHOR_FIELDS_COUNT);
				Log.i("Selected " + authorData[Data.AUTHOR_OBJECT]);
				Intent intent = new Intent(AcSearchAuthor.this, AcAuthorBooks.class);
				intent.putExtra("author", authorData[Data.AUTHOR_AUTHOR]);
				intent.putExtra("object", authorData[Data.AUTHOR_OBJECT]);
				intent.putExtra("count", authorData[Data.AUTHOR_COUNT]);
				startActivity(intent);
			}

		});
		inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		dataDownloader = new DataDownloader(this, (ProgressDialog) onCreateDialog(DIALOG_LOAD), Const.URL_ALPHABET, Const.LIST_VIEW_COUNT);
		dataDownloader.setOnCompleteLoadListener(onCompleteLoadListener());
		dataDownloader.download(Const.COUNT_ALPHABET_CHARS, Const.FILE_ALPHABET, false, false);
		searchViewText.setText(AppConfig.getString(Key.SEARCH_STRING, ""));
	}

	private void check() {
		if (searchViewText.getText().toString().trim().length() < 2) {
			Rout.toast(this, "Введите фамилию автора для поиска.", Toast.LENGTH_SHORT);
			return;
		}
		inputManager.hideSoftInputFromWindow(searchViewText.getWindowToken(), 0);

		char firstLetter = searchViewText.getText().toString().trim().toUpperCase().charAt(0);
		AppConfig.putSetting(Key.SEARCH_STRING, searchViewText.getText().toString(), AppConfig.SAVE);
		code = "";
		for (int i = 0; i < data.length; i++) {
			if (data[i].toUpperCase().charAt(0) == firstLetter) {
				String[] alphaData = dataDownloader.getDataFields(i, Data.ALPHABET_FIELDS_COUNT);
				code = alphaData[Data.ALPHABET_CODE];
				count = alphaData[Data.ALPHABET_COUNT];
//				text = alphaData[Data.ALPHABET_TEXT];
				break;
			}
		}
		if (code.length() > 0) {
			urlStr = Const.URL_ALPHABET_BOOKS + code + "&page=1&pagelen=" + count;
			fileName = Const.FILE_ROOT + '.' + code + "_alpha.txt";

			searchDownloader = new DataDownloader(this, (ProgressDialog) onCreateDialog(DIALOG_LOAD), urlStr, Const.LIST_VIEW_COUNT);
			searchDownloader.setOnCompleteLoadListener(onCompleteSearchLoadListener());
			searchDownloader.download(Integer.parseInt(count), fileName, true, false);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#finish()
	 */
	@Override
	public void finish() {
		AppConfig.putSetting(Key.SEARCH_STRING, searchViewText.getText().toString(), AppConfig.SAVE);
		super.finish();
	}

	/**
	 * @return
	 */
	private OnCompleteLoadListener onCompleteLoadListener() {
		return new OnCompleteLoadListener() {

			@Override
			public void loadComplete(boolean isLoaded) {
				if (!isLoaded) {
					if (!NetCheck.getInstance().isOnline()) {
						Rout.toast(ActivityStack.getLastActivity(), NetCheck.getInstance().getStatusStringRu(), Toast.LENGTH_LONG);
					} else {
						Rout.toast(ActivityStack.getLastActivity(), R.string.CONTENT_IS_ABSENT, Toast.LENGTH_LONG);
					}
					finish();
				} else {
					data = dataDownloader.getData();
				}
			}

		};
	}

	/**
	 * @return
	 */
	private OnCompleteLoadListener onCompleteSearchLoadListener() {
		return new OnCompleteLoadListener() {

			@Override
			public void loadComplete(boolean isLoaded) {
				if (!isLoaded) {
					if (!NetCheck.getInstance().isOnline()) {
						Rout.toast(ActivityStack.getLastActivity(), NetCheck.getInstance().getStatusStringRu(), Toast.LENGTH_LONG);
					} else {
						Rout.toast(ActivityStack.getLastActivity(), R.string.CONTENT_IS_ABSENT, Toast.LENGTH_LONG);
					}
					finish();
				} else {
					String searchString = searchViewText.getText().toString().trim().toLowerCase();
					ArrayList<String> data = searchString(searchString);
					if (data.size() == 0)
						Rout.toast(ActivityStack.getLastActivity(), "К сожалению на сайте Самиздата не найдено подходящего автора.", Toast.LENGTH_SHORT);
					adt.refreshData(data);
				}
			}

		};
	}

	/**
	 * Загрузка данных с карты.
	 */
	public ArrayList<String> searchString(String searchString) {
		Log.v("Search in file=" + fileName);
		ArrayList<String> data = new ArrayList<String>();
		if (fileName == null) {
			return data;
		}
		File file = new File(fileName);
		if (!file.exists()) {
			return data;
		}
		searchString = searchString.toLowerCase();
		// pm = new ProgressManager(this, progress, "Поиск...", fullSize, 100);
		BufferedReader in = null;
		try {
			in = new BufferedReader(new FileReader(file));
			while (in.ready()) {
				String st = in.readLine().toLowerCase();
				String[] content = Util.split(st, Data.AUTHOR_COUNT);
				if (content[Data.AUTHOR_AUTHOR].contains(searchString)) {
					data.add(st);
//					Log.i("Added " + st);
				} else {
//					Log.v("Scipped " + st);
				}
				// pm.increment(1);
			}
			in.close();
		} catch (Exception e) {
			Log.e("Failed loading " + fileName, e);
			// pm.remove();
			return data;
		}
		// pm.remove();
		return data;
	}

}
